import { isObj } from '@/utils/validate/data';

const defaultOptions = {
	type: 'text',
	mask: false,
	message: '',
	show: true,
	zIndex: 1000,
	duration: 3000,
	position: 'middle',
	forbidClick: false,
	loadingType: 'circular',
};

let queue = [];
let currentOptions = { ...defaultOptions };

function parseOptions(message) {
	return isObj(message) ? message : { message };
}

function Toast(toastOptions) {
	const options = {
		...currentOptions,
		...parseOptions(toastOptions),
	};
	options.title = options.message;
	if (options.type === 'fail') {
		options.image = require('@/static/images/components/fail.png');
	}

	const toast = uni.showToast(options);

	toast.clear = () => {
		uni.hideToast();
	};

	return toast;
}

const createMethod = type => options =>
	Toast({
		type,
		...parseOptions(options),
	});

Toast.loading = createMethod('loading');
Toast.success = createMethod('success');
Toast.fail = createMethod('fail');

Toast.clear = () => {
	queue.forEach(toast => {
		toast.clear();
	});
	queue = [];
};

Toast.setDefaultOptions = options => {
	Object.assign(currentOptions, options);
};

Toast.resetDefaultOptions = () => {
	currentOptions = { ...defaultOptions };
};

export default Toast;
